package com.yzg;

import lombok.extern.slf4j.Slf4j;

/**
 * @author misterWei
 * @create 2020年04月25号:23点32分
 * @mailbox forcontinue@163.com
 */
@Slf4j(topic = "c.waitnotify")
public class WaitNotify {
    static final Object lock = new Object();
    public static void main(String[] args) {
        Request request = new Request();
        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                System.out.println(request.request());
            },i+"t").start();

        }

            new Thread(()->{
                request.response("t");
            },"t").start();

    }

   static class Request{
        String result;
      public String request(){
          log.debug("当前线程为:"+ Thread.currentThread().getName());
          // wait 正确的使用姿势
          synchronized (lock){
              while (result == null){
                  try {
                      lock.wait();
                  } catch (InterruptedException e) {
                      log.debug("等待被其它线程打断");
                      e.printStackTrace();
                  }
              }
          }
          return result;
      }

      public void response(String value){
          synchronized (lock){
              result = value;
              lock.notifyAll();
          }
      }


   }

}
